package com.cxhc.app.api;

import com.cxhc.common.utils.PassWordUtils;
import com.cxhc.system.dto.LoginDto;
import com.cxhc.common.annotation.Anonymous;
import com.cxhc.common.constant.Constants;
import com.cxhc.common.constant.WechatConstants;
import com.cxhc.common.core.domain.R;
import com.cxhc.common.wechat.WechatUtils;
import com.cxhc.framework.web.service.SysLoginService;
import com.cxhc.framework.web.service.SysRegisterService;
import com.cxhc.system.service.ISysUserService;
import com.cxhc.system.service.app.IConfigService;
import com.google.common.collect.ImmutableMap;
import lombok.SneakyThrows;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 授权登录
 */
@RestController
@RequestMapping("/api/auth")
public class ApiAuth {
    @Resource
    private SysLoginService loginService;
    @Resource
    private SysRegisterService registerService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IConfigService configService;
    /**
     * 授权登录
     *
     * @param dto
     * @return
     */
    @SneakyThrows
    @Anonymous
    @PostMapping("/login")
    public R<Map<String,String>> login(@RequestBody @Validated LoginDto dto) {

        // 获取appid
        String appid = configService.selectValueByKey(WechatConstants.APP_ID);
        // 获取secret
        String secret = configService.selectValueByKey(WechatConstants.APP_SECRET);
        // 获取token
        String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
        if (token == null) {
            return R.fail("获取token失败");
        }
        // 获取openId
        String openId = WechatUtils.getOpenId(dto.getLoginCode(), appid, secret);
        // 获取phone 的方法
        String phone = WechatUtils.authenticatePhoneNumber(dto.getPhoneCode(), token);
        // 获取用户是否已存在【手机号是否被注册】
        boolean isExist = userService.isExistUser(phone);
        // 用户不存在
        if (!isExist) {
            // 开始注册用户 | 注册成功返回 TOKEN
            registerService.register(phone, openId, dto.getDeptId());
        }
        // 通过手机号更新OPENID
        userService.updateOpenIdByPhone(openId,phone);
        //生成默认密码
        String password = PassWordUtils.getDefaultPassword(phone);
        return R.ok(ImmutableMap.of(Constants.TOKEN, loginService.login(phone, password)));
    }

}
